package com.qzdatasoft.mcp.server.mysql.rest;

import com.qzdatasoft.mcp.server.common.IMcpToolProvider;
import com.qzdatasoft.mcp.server.mysql.service.MySqlToolService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class MySqlToolController implements IMcpToolProvider {

    private final MySqlToolService mySqlTool;

    @GetMapping("/db/queryTableNameByComment")
    @Tool(description = """
Search for table names and table comment in the database based on table comments and return in a CSV format.""")
    public String queryTableNameByComment(
            @ToolParam(description = """
Query the table name containing all input strings based on the table's comments.
Only one query condition is supported.""")
            @RequestParam(name="tableComment") String tableComment
    ){
        return mySqlTool.queryTableNameByComment(tableComment);
    }

    @GetMapping("/db/queryTableSchema")
    @Tool(description = """
Retrieve the field structure information of the specified table in a CSV format, including table name, field name,
field type, whether to allow null, field default value, and field description information""")
    public String queryTableSchema(
            @ToolParam(description = "Table names to be queried, multiple table names separated by commas")
            @RequestParam(name = "tableNames") String... tableNames
    ) {
        return mySqlTool.queryTableSchema(tableNames);
    }

    @GetMapping("/db/queryAllTableName")
    @Tool(description = """
Retrieve all table names in the database that vaguely match the specified string
and return them in CSV format. Use comma separated specified strings to represent multiple query conditions.""")
    public String queryAllTableName() {
        return mySqlTool.queryAllTableName();
    }

    @GetMapping("/db/query")
    @Tool(description = "Execute a select SQL query and return results in a JSON format.")
    public List<Map<String, Object>> query(
            @ToolParam(description = "SQL query to execute")
            @RequestParam(name = "sql") String sql
    ) {
        return mySqlTool.query(sql);
    }
}
